//
// file.js
// hs-admin
//
// Created by 区区电脑 on 2023/04/23.
//

import * as uuid from "uuid";
import { shrinkImage } from "shrinkpng";

/**
 * 首字母转大写
 *
 * @format
 * @param {*} params
 * @returns
 */

export function jsonInitialToUpcase(params) {
    if (typeof params == "object" && params) {
        let temp;
        if (Array.isArray(params)) {
            temp = [];
            for (let i = 0; i < params.length; i++) {
                temp[i] = jsonInitialToUpcase(params[i]);
            }
        } else {
            temp = {};
            for (let key in params) {
                temp[key.substring(0, 1).toLocaleUpperCase() + key.substring(1)] = jsonInitialToUpcase(params[key]);
            }
        }
        return temp;
    } else {
        return params;
    }
}

/**
 * 首字母转小写
 * @param {*} params
 * @returns
 */
export function jsonInitialToLowercase(params) {
    if (typeof params == "object" && params) {
        let temp;
        if (Array.isArray(params)) {
            temp = [];
            for (let i = 0; i < params.length; i++) {
                temp[i] = jsonInitialToLowercase(params[i]);
            }
        } else {
            temp = {};
            for (let key in params) {
                temp[key.substring(0, 1).toLocaleLowerCase() + key.substring(1)] = jsonInitialToLowercase(params[key]);
            }
        }
        return temp;
    } else {
        return params;
    }
}

// 数组转成树
export function arrayToTree(array, key = "id", pKey = "pId", childrens = "childrens") {
    const temp = {};
    for (let i = 0; i < array.length; i++) {
        temp[array[i][key]] = array[i];
    }
    for (let k in temp) {
        if (temp[k][pKey]) {
            if (temp[temp[k][pKey]]) {
                if (temp[temp[k][pKey]][childrens]) {
                    if (temp[temp[k][pKey]][childrens].indexOf(temp[k]) < 0) {
                        temp[temp[k][pKey]][childrens].push(temp[k]);
                    }
                } else {
                    temp[temp[k][pKey]][childrens] = [temp[k]];
                }
            }
        }
    }

    const tree = [];
    for (let k in temp) {
        if (!temp[k][pKey] || !temp[temp[k][pKey]]) {
            tree.push(temp[k]);
        }
    }
    return tree;
}


/**
 * 文件压缩
 * @param file
 * @param zipSize
 * @returns {Promise<unknown>}
 */
export function fileZip(file, zipSize) {
    return new Promise( async (resolve) => {
        const quality = 20; // parseInt((zipSize / (file.size / 1000)) * 100);
        console.warning("最合适的压缩率: ", quality)
        let res;
        do {
            const temp = res || file;
            res = await shrinkImage(temp, {
                quality: quality
            })
            await $sleep(100)
        } while (res.size / 1000 > zipSize)
        res.exten = file.exten;
        resolve(res)
    })
}

/**
 * 选择文件
 * @param count 多选文件数量
 * @param extension 文件类型
 * @param maxSize 允许选择文件最大内存 k
 * @param zipSize 文件压缩大小 k
 * @param success
 */
export function chooseFile({
                               count = 1,
                               extension = [],
                               maxSize,
                               zipSize,
                               success = () => {
                               }
                           }) {
    extension = extension ? extension.map(item => item.toLowerCase()) : extension;
    const form = document.createElement("form");
    const input = document.createElement("input");
    const id = "choose-file-" + uuid.v4();
    form.id = id;
    form.className = "upload-form";
    form.enctype = "multipart/form-data";
    input.name = "fileList";
    input.multiple = count > 1;
    input.accept = (extension || []).join(",");
    input.type = "file";
    input.style.width = "10px";
    input.style.height = "10px";
    input.style.opacity = "0.1";
    form.appendChild(input);
    document.body.appendChild(form);
    input.onchange = () => {
        setTimeout( async () => {
            let files = [];
            if (input.files.length > count) {
                $message.warn(`本次最大允许上传 ${count} 个文件`);
                return false;
            }
            for (let i = 0; i < input.files.length; i++) {
                if (maxSize) {
                    if (input.files[i].size / 1024 > maxSize) {
                        let maxSizeText = maxSize + "Kb"
                        if (maxSize > 1024) {
                            maxSizeText = parseFloat((maxSize / 1024).toFixed(1)) + "M"
                        }
                        $message.warn(`文件: ${input.files[i].name} 过大,请上传小于${maxSizeText} 的文件`)
                        return false;
                    }
                }
                const exten = input.files[i].name.split(".").at(-1).toLowerCase();
                input.files[i].exten = `.${exten}`;
                input.files[i]._id = uuid.v4()
                files.push(input.files[i])
            }
            // 如果设置了文件扩展名过滤
            if (extension && extension.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    if (extension.indexOf(`${files[i].exten}`) < 0) {
                        $message.error(`选择文件扩展名只能是 ${extension.join(" | ")}`)
                        return false;
                    }
                }
            }
            // 如果设置了文件压缩限制,进行自动压缩
            if (zipSize) {
                const zipFiles = [];
                for (let i = 0; i < files.length; i++) {
                    const temp = files[i];
                    if (temp.size / 1000 > zipSize) {
                        const zipFile = await fileZip(temp, zipSize);
                        if (zipFile.size === temp.size) {
                            $message.warn("文件压缩失败")
                            return false
                        }
                        zipFiles.push(zipFile)
                    } else {
                        zipFiles.push(temp)
                    }

                }
                files = zipFiles;
            }
            success(files)
            form.remove()
        }, 300);

    };
    input.click();
}

window.$apiBodyToLocal = (json) => {
    console.primary("转换成功", JSON.stringify(jsonInitialToLowercase(json))
        .replace(/\"string\"/g, null)
        .replace(/0/g, null)
        .replace(/\"/g, "")
        .replace(/null,/g, "null,\n"))
};
// excel 列头数组
export const EXCEL_COLUMN_HEADER = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ","BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ","CA","CB","CC","CD","CE","CF","CG","CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV","CW","CX","CY","CZ","DA","DB","DC","DD","DE","DF","DG","DH","DI","DJ","DK","DL","DM","DN","DO","DP","DQ","DR","DS","DT","DU","DV","DW","DX","DY","DZ","EA","EB","EC","ED","EE","EF","EG","EH","EI","EJ","EK","EL","EM","EN","EO","EP","EQ","ER","ES","ET","EU","EV","EW","EX","EY","EZ","FA","FB","FC","FD","FE","FF","FG","FH","FI","FJ","FK","FL","FM","FN","FO","FP","FQ","FR","FS","FT","FU","FV","FW","FX","FY","FZ","GA","GB","GC","GD","GE","GF","GG","GH","GI","GJ","GK","GL","GM","GN","GO","GP","GQ","GR","GS","GT","GU","GV","GW","GX","GY","GZ","HA","HB","HC","HD","HE","HF","HG","HH","HI","HJ","HK","HL","HM","HN","HO","HP","HQ","HR","HS","HT","HU","HV","HW","HX","HY","HZ","IA","IB","IC","ID","IE","IF","IG","IH","II","IJ","IK","IL","IM","IN","IO","IP","IQ","IR","IS","IT","IU","IV","IW","IX","IY","IZ","JA","JB","JC","JD","JE","JF","JG","JH","JI","JJ","JK","JL","JM","JN","JO","JP","JQ","JR","JS","JT","JU","JV","JW","JX","JY","JZ","KA","KB","KC","KD","KE","KF","KG","KH","KI","KJ","KK","KL","KM","KN","KO","KP","KQ","KR","KS","KT","KU","KV","KW","KX","KY","KZ","LA","LB","LC","LD","LE","LF","LG","LH","LI","LJ","LK","LL","LM","LN","LO","LP","LQ","LR","LS","LT","LU","LV","LW","LX","LY","LZ","MA","MB","MC","MD","ME","MF","MG","MH","MI","MJ","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NB","NC","ND","NE","NF","NG","NH","NI","NJ","NK","NL","NM","NN","NO","NP","NQ","NR","NS","NT","NU","NV","NW","NX","NY","NZ","OA","OB","OC","OD","OE","OF","OG","OH","OI","OJ","OK","OL","OM","ON","OO","OP","OQ","OR","OS","OT","OU","OV","OW","OX","OY","OZ","PA","PB","PC","PD","PE","PF","PG","PH","PI","PJ","PK","PL","PM","PN","PO","PP","PQ","PR","PS","PT","PU","PV","PW","PX","PY","PZ","QA","QB","QC","QD","QE","QF","QG","QH","QI","QJ","QK","QL","QM","QN","QO","QP","QQ","QR","QS","QT","QU","QV","QW","QX","QY","QZ","RA","RB","RC","RD","RE","RF","RG","RH","RI","RJ","RK","RL","RM","RN","RO","RP","RQ","RR","RS","RT","RU","RV","RW","RX","RY","RZ","SA","SB","SC","SD","SE","SF","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SP","SQ","SR","SS","ST","SU","SV","SW","SX","SY","SZ","TA","TB","TC","TD","TE","TF","TG","TH","TI","TJ","TK","TL","TM","TN","TO","TP","TQ","TR","TS","TT","TU","TV","TW","TX","TY","TZ","UA","UB","UC","UD","UE","UF","UG","UH","UI","UJ","UK","UL","UM","UN","UO","UP","UQ","UR","US","UT","UU","UV","UW","UX","UY","UZ","VA","VB","VC","VD","VE","VF","VG","VH","VI","VJ","VK","VL","VM","VN","VO","VP","VQ","VR","VS","VT","VU","VV","VW","VX","VY","VZ","WA","WB","WC","WD","WE","WF","WG","WH","WI","WJ","WK","WL","WM","WN","WO","WP","WQ","WR","WS","WT","WU","WV","WW","WX","WY","WZ","XA","XB","XC","XD","XE","XF","XG","XH","XI","XJ","XK","XL","XM","XN","XO","XP","XQ","XR","XS","XT","XU","XV","XW","XX","XY","XZ","YA","YB","YC","YD","YE","YF","YG","YH","YI","YJ","YK","YL","YM","YN","YO","YP","YQ","YR","YS","YT","YU","YV","YW","YX","YY","YZ","ZA","ZB","ZC","ZD","ZE","ZF","ZG","ZH","ZI","ZJ","ZK","ZL","ZM","ZN","ZO","ZP","ZQ","ZR","ZS","ZT","ZU","ZV","ZW","ZX","ZY","ZZ"];

/**
 * 强密码校验
 * @param value
 * @returns {boolean}
 */
export const checkPassword = (value) => {
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=])(?!.*(012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210|000|111|222|333|444|555|666|777|888|999)).{8,}$/
    return reg.test(value)
}
/**
 * 手机号校验
 * @param value
 * @returns {boolean}
 */
export const checkPhone = (value) => {
    const reg = /^1[0123456789]\d{9}$/;
    return reg.test(value)
}